<?php defined('SYSPATH') OR die('No direct access allowed.');

class Model_Cms_Banners extends Model {
	
public function get_banners()
	{
		return DB::Select()->from('banners')
					->execute();
	}
	
	public function get_banner($id)
	{
		return DB::Select()->from('banners')
					->where('id','=',$id)
					->execute()->current();
	}
	
	// konkretna jednostka banera
	public function get_unit($id)
	{
		return DB::Select()->from('banner_units')
					->where('id','=',$id)
					->execute()->current();
	}
	
	// lista jednostek banera
	public function get_units($banner_id)
	{
		return DB::Select()->from('banner_units')
					->where('banner_id','=',$banner_id)
					->order_by('order')
					->execute();
	}
	
	public function save_banner($id,$file,$url)
	{
		if($file == 'no_banner')
		{
			$filename = '';
			$ext = 'wth';
		}else{
			$ext = strtolower(substr($file, strrpos($file, '.') + 1));
			$parts = explode(".".$ext,$file);
			$filename = $parts[0];
		}
		DB::update('banners')
				->set(array('file'=>$filename,'ext'=>$ext,'url'=>$url))
				->where('id','=',$id)
				->execute();
	}
	
	public function count_units($id)
	{
		$count = DB::select(array('COUNT("*")', 'total_count'))
				->from('banner_units')
				->where('banner_id','=',$id)
				->execute()->get('total_count');
		return $count;
	}
	
	public function insert_banner($banner_id,$filename)
	{					
		$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
		//$user = Auth::instance()->get_user();
		
		// ilosc jednostek bannera
		//$current = DB::Select('MAX(order)')->from('banner_units')->where('banner_id','=',$banner_id)->execute()->current();
		$current = $this->count_units($banner_id);
		$order = $current + 1;
		
		DB::insert('banner_units', array('banner_id','name','ext','created_at','order'))->values(array($banner_id,$filename,$ext,time(),$order))->execute();
	}
	
	public function change_url($id,$url)
	{					
		DB::update('banner_units')
				->set(array('url'=>$url))
				->where('id','=',$id)
				->execute();
	}
}
?>